package renhai.util;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import renhai.util.error.BusinessException;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

/**
 * SpringMVC统一异常处理
 * 注:@ControllerAdvice为Controller层增强器,其只能处理Controller层抛出的异常;
 * 由于代码间的层级调用机制  、异常的处理机制等,所以这里处理Controller层的异常,就相当于
 * 处理了全局异常
 * <p>
 * 注: @RestControllerAdvice等同于  @ResponseBody 加上 @ControllerAdvice
 *
 * @author JustryDeng
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 具体的处理异常的逻辑
     * 注:@ExceptionHandler的value属性指定要处理哪些异常;
     *
     * @param ex 捕获到的异常
     * @return 返回给前端的data
     */
    @ExceptionHandler(value = {ConstraintViolationException.class})
    public ResponseContext<String> constraintViolationException(ConstraintViolationException ex) {
/*        Map<String, Object> resultMap = new HashMap<>(4);
            resultMap.put("msg", "@Valid约束在参数上，直接校验接口的参数时异常 -> " + ex.getMessage());
            resultMap.put("code", "1");*/
        return new ResponseContext<>(ex.getMessage(), 2, 600);
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResponseContext<String> methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        /*Map<String, Object> resultMap = new HashMap<>(4);
            resultMap.put("msg", "@Validated约束在类上，直接校验接口的参数时异常 -> " + ex.getMessage());
            resultMap.put("code", "1");*/
        return new ResponseContext<>(ex.getMessage(), 2, 601);
    }

    @ExceptionHandler(value = {BusinessException.class})
    public ResponseContext<String> businessException(BusinessException ex) {
        Map<String, Object> resultMap = new HashMap<>(4);
        resultMap.put("msg", "自定义异常：" + ex.getMessage());
        resultMap.put("code", "1");
        ex.printStackTrace();
        return new ResponseContext<>(ex.getMessage(), 2, 602);
    }

    @ExceptionHandler(value = {Exception.class})
    public ResponseContext<String> exception(Exception ex) {
        Map<String, Object> resultMap = new HashMap<>(4);
        resultMap.put("msg", "系统异常：" + ex.getMessage());
        resultMap.put("code", "1");
        ex.printStackTrace();
        return new ResponseContext<>(ex.getMessage(), 2, 603);
    }

}